package com.steakliu.sun.buffer;

import com.alibaba.fastjson.JSONObject;
import com.lmax.disruptor.EventHandler;
import com.steakliu.sun.buffer.api.DataBuffer;
import com.steakliu.sun.buffer.disuptor.DataEvent;
import com.steakliu.sun.buffer.disuptor.DataEventPublisher;
import com.steakliu.sun.buffer.disuptor.DataEventPublisherFactory;
import com.steakliu.sun.protocol.SunProtocol;
import com.steakliu.sun.spi.annotation.Join;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 功能说明： disruptor缓冲实现
 * <p>
 * Original @Author: steakliu-刘牌, 2023-02-09  15:50
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
@Join
@Deprecated
public class DisruptorDataBuffer<T> implements DataBuffer<T>, EventHandler<DataEvent<T>> {

    private final Logger LOGGER = LoggerFactory.getLogger(DisruptorDataBuffer.class);

    private SunProtocol<T> dataEvent;

    private DataEventPublisher dataEventPublisher;

    @Override
    public void push(SunProtocol<T> protocol) {
        dataEventPublisher.publishEvent(protocol);
    }

    @Override
    public SunProtocol<T> take() {
       if (null != dataEvent){
           LOGGER.info("dataEvent   : {}",dataEvent);
           return dataEvent;
       }
       return null;
    }

    @Override
    public void init(int capacity) {
        DataBuffer.super.init(capacity);
        this.dataEventPublisher = DataEventPublisherFactory.getInstance();
    }

    @Override
    public void onEvent(DataEvent<T> event, long sequence, boolean endOfBatch) throws Exception {
        LOGGER.info("from disruptor message : {}", JSONObject.toJSONString(event));
        this.dataEvent = event.getProtocol();
    }
}
